package org.Agenty2012.Agent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.Agenty2012.Agent.ColorPickerDialog.OnColorChangedListener;
import org.apache.http.HttpConnection;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AgentActivity extends Activity {
    final MyColorListener myColorListener = new MyColorListener();
    private String sid;
    private boolean started = true;
    private String address = "";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button button1main = (Button) findViewById(R.id.button1);

        button1main.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Dialog colorDialog = new ColorPickerDialog(AgentActivity.this, myColorListener, 0xFFFF0000);
                colorDialog.show(); 
            }

        });

        Button button1start = (Button) findViewById(R.id.button2);
    }
    
    public void startGPS(View view)
    {
    	started = !started;
    	TextView textViewError = (TextView) findViewById(R.id.textviewerror);
    	boolean wasChanged = myColorListener.getChange();
    	EditText edit = (EditText) findViewById(R.id.editText1);
    	String name = edit.getText().toString();
    	EditText server = (EditText)findViewById(R.id.editText2);
    	address = server.getText().toString();
    	if (started)
    	{
    	    //stopService(new Intent(AgentActivity.this, GpsService.class));
        	Intent intent = new Intent(this, GpsService.class);
        	intent.putExtra("sid", sid);
        	intent.putExtra("address", address);
    	    stopService(intent);
    	    Button button1start = (Button) findViewById(R.id.button2);
    	    button1start.setText("Start");
    	    return;
    	}
    	if(address == "")
    	{
    		textViewError.setText("Please enter server address");
    		textViewError.setTextColor(0xFFFF0000);
    		return;
    	}
    	if (name == "")
    	{
    		textViewError.setText("Please enter name");
    		textViewError.setTextColor(0xFFFF0000);
    		return;
    	}
    	if (!wasChanged)
    	{
    		textViewError.setText("Please select color");
    		textViewError.setTextColor(0xFFFF0000);
    		return;
    	}
    	
    	if (sid == null){
    		sid = getSid(name,hex2Rgb(String.valueOf(myColorListener.getCurrentColor())));
    		int count = 0;
    		int count1 = 0;
    		int count2 = 0;
    		int count3 = 0;
    		int count4 = 0;
    		int res = 0;
    		for (char c : sid.toCharArray()){
    			count++;
    			if (count1==2)
    				count3++;
    			if (c == '>'){
    				count1++;
    				if (count1 == 2)
    					res = count;
    			}
    			if (c == '<'){
    				count2++;
    				if (count2 == 3)
    					count4 = count;
    			}
    			
    			if (count2 == 3)
    				break;
    		}
    		count3-=1;
    		sid = sid.substring(res, res+count3);
    	}
    	Intent intent = new Intent(this, GpsService.class);
    	intent.putExtra("sid", sid);
    	intent.putExtra("address", address);
	    startService(intent);
	    Button button1start = (Button) findViewById(R.id.button2);
	    button1start.setText("Stop");
    	
    }
    
    public String getSid(String name, String color) {
        // Create a new HttpClient and Post Header
    	//String data = "nickname=" + name + "&color=" + color;
    	//String baseUrl = "http://10.0.2.2:1785/Locations.asmx"; 
    	String baseUrl =  address + "/Locations.asmx";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(baseUrl+"/Register");// + "?nickname=" + name + "&color=" + color);
        
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("nickname", name));
            nameValuePairs.add(new BasicNameValuePair("color", color));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httppost.setHeader("Content-type", "application/x-www-form-urlencoded");

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
        	//HttpUriRequest uri = new HttpUriRequest();
        	//HttpResponse reposnse = httpclient.execute(null);
            return inputStreamToString(response.getEntity().getContent()).toString();
            
        } catch (ClientProtocolException e) {
        	Log.d(getClass().getSimpleName(),"ZJEBALO SIEM");
        	e.printStackTrace();
            // TODO Auto-generated catch block
        } catch (IOException e) {
        	Log.d(getClass().getSimpleName(),"ZJEBALO SIEM");
        	e.printStackTrace();
            // TODO Auto-generated catch block
        }
        return null;
    } 
    
    
    private StringBuilder inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        // Read response until the end
        try {
			while ((line = rd.readLine()) != null) { 
			    total.append(line); 
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        // Return full string
        return total;
    }
    
    public static String hex2Rgb(String colorStr) {
    	String result;
    	try{
    	result = new String("rgb(" + 
                Integer.valueOf( colorStr.substring( 1, 3 ), 16 ).toString() + "," +
                Integer.valueOf( colorStr.substring( 3, 5 ), 16 ).toString() + "," +
                Integer.valueOf( colorStr.substring( 5, 7 ), 16 ).toString() + ")" );
    	}catch(Exception e){
    		result = new String("rgb(" + 255 + "," + 128 + "," + 64 + ")");
    	}
        return result;
    }


}

